#include "GameScene.h"
#include "MenuLayer.h"
#include "MainScene.h"

GameScene::GameScene()
: pBackgroundLayer(NULL)
, pPhysicsLayer(NULL)
, pScoreLayer(NULL)
, pMenuLayer(NULL)
, pOptionMenuLayer(NULL)
, pEndLayer(NULL)
{
}

GameScene::~GameScene()
{
}

GameScene * GameScene::create()
{
  GameScene * pScene = new GameScene();
  if (pScene && pScene->init())
  {
    pScene->autorelease();
    return pScene;
  }
  else
  {
    CC_SAFE_DELETE(pScene);
    return NULL;
  }
}

bool GameScene::init()
{
  do
  {
    CC_BREAK_IF(!CCScene::init());

    CCSpriteFrameCache * pCache = CCSpriteFrameCache::sharedSpriteFrameCache();
    pCache->addSpriteFramesWithFile("game.plist");

    pBackgroundLayer = BackgroundLayer::create();
    CC_BREAK_IF(!pBackgroundLayer);
    addChild(pBackgroundLayer);

    pPhysicsLayer = PhysicsLayer::create();
    CC_BREAK_IF(!pPhysicsLayer);
    pPhysicsLayer->setBackgroundLayer(pBackgroundLayer);
    pPhysicsLayer->setGameLayerManager(this);
    addChild(pPhysicsLayer);

    pScoreLayer = ScoreLayer::create();
    CC_BREAK_IF(!pScoreLayer);
    addChild(pScoreLayer);

    pMenuLayer = MenuLayer::create();
    CC_BREAK_IF(!pMenuLayer);
    pMenuLayer->setGameLayerManager(this);
    addChild(pMenuLayer);

    pOptionMenuLayer = OptionMenuLayer::create();
    CC_BREAK_IF(!pOptionMenuLayer);
    pOptionMenuLayer->setGameLayerManager(this);
    pOptionMenuLayer->setVisible(false);
    addChild(pOptionMenuLayer);

    pEndLayer = EndLayer::create();
    CC_BREAK_IF(!pEndLayer);
    pEndLayer->setGameLayerManager(this);
    pEndLayer->setVisible(false);
    addChild(pEndLayer);

    return true;
  } while(0);
  return false;
}

void GameScene::startGame()
{
}

void GameScene::stopGame()
{
}

void GameScene::resumeGame()
{
  pPhysicsLayer->scheduleUpdate();
  pOptionMenuLayer->setVisible(false);
}

void GameScene::pauseGame()
{
  if (pEndLayer->isVisible())
    return;
  pPhysicsLayer->unscheduleUpdate();
  pOptionMenuLayer->setVisible(true);
}

void GameScene::exitGame()
{
  CCDirector::sharedDirector()->replaceScene(MainScene::create());
}

void GameScene::endGame()
{
  pPhysicsLayer->unscheduleUpdate();
  pEndLayer->setVisible(true);
}

void GameScene::retryGame()
{
  pEndLayer->setVisible(false);
  pPhysicsLayer->restart();
  pScoreLayer->restart();
  pPhysicsLayer->scheduleUpdate();
}

void GameScene::refreshScore(ScoreType type, int value)
{
  pScoreLayer->refreshScore(type, value);
}
